package routers

import (
	"app/internal/web/controllers"
	"github.com/gin-gonic/gin"
	"net/http"
)

func Cross() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method
		//fmt.Println(method)
		c.Header("Access-Control-Allow-Origin", "*")
		c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token")
		c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, PATCH, DELETE")
		c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
		c.Header("Access-Control-Allow-Credentials", "true")
		// 放行所有OPTIONS方法，因为有的模板是要请求两次的
		if method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
		}
		c.Next()
	}
}

func Engine() http.Handler {

	return NewEngine()
}

func NewEngine() *gin.Engine {

	gin.DisableConsoleColor()
	routers := gin.New()
	routers.Use(gin.Logger(), gin.Recovery(), Cross())
	return routers
}

func AddRouterHandler(http *http.Server, handler gin.HandlerFunc) {
	http.Handler.(*gin.Engine).Use(handler)
}

func RegPostController(http *http.Server, relativePath string, c controllers.ControllerInterface) {
	http.Handler.(*gin.Engine).POST(relativePath, c.Post)
}

func RegGetController(http *http.Server, relativePath string, c controllers.ControllerInterface) {
	http.Handler.(*gin.Engine).GET(relativePath, c.Get)
}

func RegDeleteController(http *http.Server, relativePath string, c controllers.ControllerInterface) {
	http.Handler.(*gin.Engine).DELETE(relativePath, c.Delete)
}

func RegPatchController(http *http.Server, relativePath string, c controllers.ControllerInterface) {
	http.Handler.(*gin.Engine).PATCH(relativePath, c.Patch)
}

func RegPutController(http *http.Server, relativePath string, c controllers.ControllerInterface) {
	http.Handler.(*gin.Engine).PUT(relativePath, c.Put)
}

func RegOptionsController(http *http.Server, relativePath string, c controllers.ControllerInterface) {
	http.Handler.(*gin.Engine).OPTIONS(relativePath, c.Options)
}

func RegHeadController(http *http.Server, relativePath string, c controllers.ControllerInterface) {
	http.Handler.(*gin.Engine).HEAD(relativePath, c.Head)
}
